﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MyWPF.Models.TCP.TCPServer
{
    public class TCPServerHelper :ITCPServer
    {

        IPEndPoint server;
        TcpListener listener;

        public void Connect(TCPServerContext ServerContext)
        {
            IPAddress ipAddress = IPAddress.Any;
            server = new IPEndPoint(ipAddress, ServerContext.Port);

            //打开监听
            listener = new TcpListener(server);
            listener.Start();

            while (true)
            {
                Console.WriteLine("Waiting for client connections...");

                // 等待客户端连接
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine($"Client connected from {client.Client.RemoteEndPoint}");

                // 读取客户端请求数据
                NetworkStream stream = client.GetStream();
                byte[] buffer = new byte[client.ReceiveBufferSize];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string request = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Received request: {request}");

                // 处理请求并返回响应数据
                string response = $"Hello from server at {DateTime.Now}";
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                stream.Write(responseBytes, 0, responseBytes.Length);
                Console.WriteLine($"Sent response: {response}");

                // 关闭连接
                client.Close();
            }
        }
    }
}
